package top.continew.ai.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;
import top.continew.ai.config.ChatApp;

import java.io.IOException;

/**
 * @author: lonni
 * @CreateTime: 2025-08-20  22:33
 * @Description:
 */
@RestController
@RequestMapping("ai/chat")
@CrossOrigin
public class ChatAiController {


    @Autowired
    private ChatApp chatApp;


    /**
     * 同步问答
     *
     * @param message
     * @param conversationId
     * @return
     */
    @GetMapping("chat_sync")
    public String doChatSync(String message, String conversationId) {
        return chatApp.doChat(message, conversationId);
    }


    /**
     * 异步问答
     * 不支持支持自定义事件类型
     * @param message
     * @param conversationId
     * @return
     */
    @GetMapping(value = "chat_stram",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> doChatByStream(String message, String conversationId, HttpServletResponse response) {
       response.setCharacterEncoding("utf-8");
        return chatApp.doChatByStream(message, conversationId);
    }


    /**
     * 异步问答
     * @param message
     * @param conversationId
     * @return
     */
    @GetMapping("chat_stram_event")
    public Flux<ServerSentEvent<String>> doChatByStreamEvent(String message, String conversationId) {
        return chatApp.doChatByStream(message, conversationId)
                .map(chunk->ServerSentEvent.<String>builder()
                        .data(chunk)
                        .event("message")
                        .build());

    }
    @GetMapping(value = "chat_sse_emitter")
    public SseEmitter doChatWithServerSseEmitter(String message, String chatId) {
        // 创建一个超时时间较长的 SseEmitter
        SseEmitter sseEmitter = new SseEmitter(180000L); // 3 分钟超时
        // 获取 Flux 响应式数据流并且直接通过订阅推送给 SseEmitter
        chatApp.doChatByStream(message, chatId)
                .subscribe(chunk -> {
                    try {
                        sseEmitter.send(chunk);
                    } catch (IOException e) {
                        sseEmitter.completeWithError(e);
                    }
                }, sseEmitter::completeWithError, sseEmitter::complete);
        // 返回
        return sseEmitter;
    }


}
